import {Component} from '@angular/core';
import {NavController, NavParams} from 'ionic-angular';
import {Helper} from "../../common/Helper";
import {ProductProvider} from "../../providers/product/product";
import {UserProvider} from "../../providers/user/user";
import {HttpProvider} from "../../common/http";

@Component({
  selector: 'page-pay',
  templateUrl: 'pay.html',
})
export class PayPage {

  product: any = {}
  user: any = {}
  money: number

  constructor(public navCtrl: NavController,
              private navParams: NavParams,
              private productProvider: ProductProvider,
              private http: HttpProvider,
              private helper: Helper,
              private userProvider: UserProvider) {
    this.getProductDetail()
  }

  ionViewWillEnter() {
    Helper.setStatusBarDefault()
  }

  getProductDetail() {
    this.productProvider.getDetail({
      loading: false,
      data: {
        id: this.navParams.get('id')
      },
      success: (d) => {
        this.getUserInfo()
        this.product = d
      }
    })
  }

  getUserInfo() {
    this.userProvider.getUserInfo({
      loading: false,
      success: (data) => {
        this.user = data
        console.log(this.user)
      }
    })
  }

  checkMoney() {
    let money = Number(this.money)
    let free = Number(this.user.free)
    let balanceAmount = Number(this.product.balanceAmount)
    let minInvestmentAmount = Number(this.product.minInvestmentAmount)
    if (money >= minInvestmentAmount) {
      if (money > free) {
        this.http.toastMsg('购买金额不能超过可用余额')
        return false
      }
      if (money > balanceAmount) {
        this.http.toastMsg('购买金额不能超过产品余量')
        return false
      }
      return true
    } else {
      this.http.toastMsg('购买金额需大于起投金额')
      return false
    }
  }

  allMoney() {
    let free = Number(this.user.free)
    let balanceAmount = Number(this.product.balanceAmount)
    let minInvestmentAmount = Number(this.product.minInvestmentAmount)
    if (free >= minInvestmentAmount && free <= balanceAmount) {
      this.money = free
    } else if (free < minInvestmentAmount) {
      this.http.toastMsg('余额小于起投金额，请先充值')
    } else if (free > balanceAmount) {
      this.money = balanceAmount
      this.http.toastMsg('购买金额不能超过产品余量')
    }
  }

  submit() {
    if (this.checkMoney()) {
      this.productProvider.investBid({
        data: {
          loanId: this.navParams.get('id'),
          investAmount: this.money
        },
        success: (d) => {
          console.log(d)
          this.helper.alert({
            title: '投资成功',
            cssClass: 'g-alert-custom',
            enableBackdropDismiss: false,
            buttons: [{
              text: '确认',
              handler: () => {
                this.navCtrl.pop()
              }
            }]
          })
        }
      })
    }
  }

}
